﻿using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;

using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
using System.Data.Entity.Migrations;

namespace ccq.akisi.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        static ApplicationDbContext()
        {
            Database.SetInitializer<ApplicationDbContext>(new AkisiInitializer());
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

    public class AkisiInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
    {
        protected override void Seed(ApplicationDbContext context)
        {
            // Identity Roles
            context.Roles.AddOrUpdate(r => r.Name,
                new IdentityRole { Name = "Administrator" },
                new IdentityRole { Name = "Guest" }
            );

            context.SaveChanges();

            // Common Users
            var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)) { PasswordValidator = new MinimumLengthValidator(1) };

            if (UserManager.FindByName("keith") == null)
            {
                var user = new ApplicationUser { UserName = "keith", Email = "keith@clockwiseq.com" };
                var result = UserManager.Create(user, "akisiadmin!");

                if (result.Succeeded)
                {
                    UserManager.AddToRole(user.Id, "Administrator");
                }
            }

            context.SaveChanges();

            base.Seed(context);
        }
    }

}